package cn.sskxyz.security.core.config;

import cn.sskxyz.security.core.property.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
@ConditionalOnProperty(prefix = "system.security", name = "token-type", havingValue = "uuid", matchIfMissing = true)
public class UUIDTokenConfigure {
    @Autowired
    private SecurityProperties securityProperties;

    @Bean
    @ConditionalOnMissingBean(TokenStore.class)
    public TokenStore tokenStore() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(securityProperties.getRedis().getHost());
        configuration.setPort(securityProperties.getRedis().getPort());
        configuration.setPassword(securityProperties.getRedis().getPassword());
        configuration.setDatabase(securityProperties.getRedis().getDatabase());
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration);
        factory.afterPropertiesSet();
        return new RedisTokenStore(factory);
    }

    @Bean
    @ConditionalOnMissingBean(DefaultTokenServices.class)
    public DefaultTokenServices tokenService() throws Exception {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setRefreshTokenValiditySeconds(30 * 24 * 3600);
        tokenServices.setAccessTokenValiditySeconds(7200);
        tokenServices.afterPropertiesSet();
        return tokenServices;
    }
}
